<?php
class VideoYoutubeController extends AdminController {
    public function init() {
        parent::init();
        if (Yii::app()->user->id != 1) {
            $this->redirect(array('/admin/meme/index'));
        }
    }

    public function actionAdmin() {
        $limit = 20;

        $criteria = new CDbCriteria();
        $criteria->compare('file', 'http', true);
        $criteria->limit = $limit;
        $criteria->order = 'created_at DESC';

        $memes = Meme::model()->findAll($criteria);

        $count = Meme::model()->count($criteria);
        $pages = new CPagination($count);

        // results per page
        $pages->pageSize = $limit;
        $pages->applyLimit($criteria);

        $this->render('../meme/index', array(
                'memes' => $memes,
                'pages' => $pages,
            ));
    }

    public function actionUpdate($id='') {
        $model = !empty($id) ? $this->loadModel($id) : new VideoYoutube();
        $mode = empty($id) ? 'add' : 'edit';

        if(isset($_POST['ajax']) && $_POST['ajax'] == 'videoyoutube-form')
        {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }

        // collect user input data
        if (isset($_POST['VideoYoutube'])) {
            $modelMeme = new Meme();
            $modelMeme->attributes = $_POST['VideoYoutube'];
            $modelMeme->user_fk = 1;
            $modelMeme->is_active = 1;
            $modelMeme->is_featured = 1;
            $modelMeme->is_published = 1;
            $modelMeme->file = $_POST['VideoYoutube']['linkFile'];
            $modelMeme->created_at = new CDbExpression('NOW()');
            $uploadImage = Utility::uploadImage($modelMeme, 'image');
            $modelMeme->image = $uploadImage;

            // validate user input and redirect to the previous page if valid
            if (!$modelMeme->save(false)) {
                Yii::log(CVarDumper::dump($modelMeme->getErrors(), 10, true), CLogger::LEVEL_WARNING, 'warning');
            }
            Utility::setFlash('Video Youtube ' . $mode . 'ed successfully.', 'success');
            $this->redirect($this->createUrl('VideoYoutube/update'));
        }

        $this->render('form', array(
            'model' => $model,
            'mode' => $mode,
            'id' => $id,
        ));
    }

    public function loadModel($id) {
        $model = Meme::model()->findByPk($id);
        if ($model === null) {
            throw new CHttpException(404, 'The requested page does not exist.');
        }

        return $model;
    }

    public function actionDeleteImage() {
        if (Yii::app()->request->isPostRequest):
            $imageName = Yii::app()->request->getPost('imageName');
            $model = Yii::app()->request->getPost('model');
            $image = Yii::app()->request->getPost('colImage') ? Yii::app()->request->getPost('colImage') : 'image';
            if ($imageName):
                $params = array(
                    'imageName'   => $imageName,
                    'id'          => Yii::app()->request->getPost('imageID'),
                    'model'       => $model,
                    'colFileName' => $image,
                    'folder'      => 'memes/VideoYoutube'
                );
                self::deleteImage($params);
                echo CJSON::encode("Image was deleted");
                Yii::app()->end();
            endif;
        endif;
    }

    protected function deleteImage($params) {
        $data = $params['model']::model()->find('meme_id=:id', array(':id' => $params['id']));
        if ($data) {
            $fileName = isset($params['colFileName']) ? $params['colFileName'] : 'image';
            $typeFile = explode(',', $data[$fileName]);
            if (in_array($params['imageName'], $typeFile)) {
                $diffTypeFile = array_diff($typeFile, array($params['imageName']));
                $typeFile     = implode(',', $diffTypeFile);
                $params['model']::model()->updateByPk($params['id'], array($params['colFileName'] => $typeFile));
                unlink($params['folder'] . '/' . $params['imageName']);
            } else {
                foreach ($typeFile as $file) {
                    if (!empty($file)) {
                        unlink($params['folder'] . '/' . $file);
                    }
                }
            }
        }
    }
}